﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace ScheduleMaker.DB
{
    //Ta klase mysle zeby przerobic troche
    //zmienic na public abstract class AbstractDAO<T>
    //i pozniej dziedziczyc po tym, zrobic UserDAO exteds AbstractDAO<User> itp
    //tam dodac metody typu findByFirstname itd.
    public class DAO
    {
        protected Configuration config;
        protected ISessionFactory sessionFactory;
        protected ISession session;
        protected ITransaction transaction;
        private Boolean transactionBegan;

        protected void configure()
        {
            config = new Configuration();
            //TODO: znalezc lepszy sposob na dodanie mappingow, ten jest brzydki
            config.AddAssembly(typeof(ScheduleMaker.DB.Domain.LevelSchool).Assembly);
            sessionFactory = config.BuildSessionFactory();
        }

        protected void createSession()
        {
            if (sessionFactory == null)
            {
                configure();
            }
            session = sessionFactory.OpenSession();
        }

        protected void createTransaction()
        {
            if (session == null)
            {
                createSession();
            }
            transaction = session.BeginTransaction();
            transactionBegan = true;
        }

        protected void commitTransaction()
        {
            if (transactionBegan)
            {
                transaction.Commit();
            }
        }

        public void closeSession()
        {
            session.Close();
            session = null;
        }

        public void save(Object entity){
            createTransaction();
            session.Save(entity);
            commitTransaction();
            closeSession();
        }

        public T getById<T>(int id)
        {
            T entity;
            createSession();
            entity = session.Get<T>(id);
            closeSession();
            return entity;
        }

    }
}
